<template>
	<view class="content">


		<z-paging>
			<!--  -->
			<view class="" slot="top">
				<!-- #ifdef APP -->
				<NavBarCommon></NavBarCommon>
				<!-- #endif -->
				<view class="claimBox" style=" position: relative;">
					<image style="position: absolute;left: 2%;" src="@/static/home/right.png" class="claim1" @click="goBack" />
					<view class="claim2">{{ $t('invitationcode') }}</view>
				</view>
			</view>
			<!--  -->
			<view class="">
				<u-gap></u-gap>
				<view class="headerBox">
					<view class="leftBox">
						<image src="/static/home/one.png" class="oneImage" />
						<view class="hello">{{ walletAddress ? formatPublicKey(walletAddress) : "" }}</view>
					</view>
					<view class="rightBox" style="margin-right: 20px;">
						<image v-if="model.role == 1" src="/static/invited/yellow.png" class="oneImage" />
						<image v-if="model.role == 2" src="/static/invited/blue.png" class="oneImage" />
						<image v-if="model.role == 3" src="/static/invited/white.png" class="oneImage" />
					</view>
					<!--  -->
					<!-- <text v-if="model.role == 1">基金会</text>
				<text v-if="model.role == 2">创世区块</text>
				<text v-if="model.role == 3">合伙人</text> -->
				</view>
				<!--  -->
				<view class="one" style="order: 1">
					<u-gap height="15"></u-gap>
					<view class="recharge-header flex flex-column">
						<view class="flex  items-center justify-between">
							<view class="recharge-header-title">
								<text>{{ $t('Purchaseinvitationcode') }}</text>
							</view>
							<view class="recharge-header-title" @click="go">
								<text style="color: #999999;font-size: 16px;line-height: 16px;">{{ $t('purchaserecord') }}</text>
							</view>
						</view>
					</view>
					<u-gap height="15"></u-gap>
					<view class="recharge-search ">
						<view class="mev-follow-robot-search-wrap">
							<view class="mev-follow-robot-search-wrap-select flex">
								<image class="mev-follow-robot-search-wrap-select-icon"
									style="width: 58rpx;height: 58rpx;margin: 0 20rpx;" src="/static/invited/logo.png"
									mode="scaleToFill" />
								<text class="label mev-follow-robot-search-wrap-select-label">{{ $t('unitprice') }} : {{ model.price
									}}</text>
								<text class="label mev-follow-robot-search-wrap-select-label">rmb</text>
							</view>
							<view class="mev-follow-robot-search-wrap-input" style="margin-left: 30rpx;">
								<u-number-box color="#ffffff" bgColor="#29313C" iconStyle="color: #fff" v-model="model.amount"
									:min="model.miniAmount"></u-number-box>
							</view>
						</view>
					</view>
					<u-gap height="10"></u-gap>
				</view>
				<!-- 提示 -->
				<view class="recharge-tag">
					<view class="recharge-tag-left" style="margin-left: 20rpx;">
						<text>VIP{{ model.role }} {{ model.amount || 0 }} {{ $t('invitationcode') }}{{ $t('purchase') }}!</text>
					</view>
					<view class="recharge-tag-right">
						<text class="">
							<!-- 请使用 USDC支付 -->
							{{ $t('pleaseuse') }} USDT {{ $t('payment') }}
						</text>
					</view>
				</view>
			</view>
			<!--  -->

			<view class="" slot="bottom">
				<view class="flex " style="height: 110rpx;">
					<view class="flex-1 " style="background-color: #29313C;">
						<view class="flex items-center  " style="height: 110rpx;justify-content: end;margin-right: 40rpx;">
							<view class="" style="color: #fff;font-size: 36rpx;line-height: 110rpx;">{{ $t('total') }}:</view>
							<!-- <view class="" style="color: #E4393C;font-size: 36rpx;line-height: 110rpx;">￥{{ totalPrice }}</view> -->
							<view class="" style="color: #E4393C;font-size: 36rpx;line-height: 110rpx;">${{ totalPrice }}</view>
						</view>
					</view>
					<button @click="getBtn" :disabled="isButtonDisabled" :loading='isButtonDisabled'
						class=" items-center  justify-center"
						style="background-color: #141A23;width: 220rpx;color: #fff;font-size: 36rpx;line-height: 110rpx;text-align: center;">
						{{ $t('Gotosettle') }}
					</button>
				</view>
			</view>
		</z-paging>
	</view>
</template>

<script>
import {
	inviteCodeinfo,
	getUserInfo,
	inviteCodepurchase,
	inviteCodetransaction
} from '@/api/index.js'
import {
	Connection,
	Transaction,
	SystemProgram,
	LAMPORTS_PER_SOL,
	PublicKey,
	TOKEN_PROGRAM_ID
} from '@solana/web3.js'
// import { getAccount, getAssociatedTokenAddress } from "@solana/spl-token";
import env from '@/utils/env.js'
const NETWORK_URL = env.rpcURL
const connection = new Connection(NETWORK_URL);

function convertRMBToUSD(rmbAmount, exchangeRate) {
	let usdAmount = rmbAmount / exchangeRate;
	return usdAmount.toFixed(2); // 保留两位小数
}

const mintAddress = env.usdtURL


export default {
	data() {
		return {
			isButtonDisabled: false,
			balance: 0,
			usdcLimit: '',
			signature: "",
			walletAddress: uni.getStorageSync('walletAddress'),
			model: {
				address: "",
				role: "",
				amount: "",
				price: "",
				price_USD: '',
				miniAmount: ''
			}
		};
	},
	computed: {
		totalPrice() {
			// let exchangeRate = 7.0; // 汇率可以根据实际情况进行调整
			if (this.model.price == 0) return 0
			let rmbAmount = this.model.amount * this.model.price_USD
			// let usdAmount = convertRMBToUSD(rmbAmount, exchangeRate);
			return Number(rmbAmount).toFixed(4)
		}
	},
	methods: {
		go() {
			uni.navigateTo({
				url: '/pages/invitedList/invitedList'
			})
		},
		// rpc 查询我的 USDC 余额
		async getUsdcBalance() {
			let walletAddress = uni.getStorageSync('walletAddress')
			// let mintAddress = 'BXXkv6zRCVdFz84M9GbyMZJrmfD3s7gmxgZkKzY4oPp'// Devnet USDC

			// let mintAddress = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'// Devnet USDC
			// let mintAddress = 'E7x8RPSmWVrY4opCL376f7pAkU76cWwpVGnhYxA1E5T5'// Devnet USDT

			// let mintAddress = 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'// Main USDT

			try {
				const tokenAccounts = await connection.getParsedTokenAccountsByOwner(
					new PublicKey(walletAddress), {
					mint: new PublicKey(mintAddress)
				}
				);
				if (tokenAccounts.value.length === 0) {
					console.log("未找到该 token 的账户");
					return 0;
				}

				const amount = tokenAccounts.value[0].account.data.parsed.info.tokenAmount;
				const balance = amount.uiAmount;
				console.log(`Token 余额: ${balance}`);
				this.balance = balance
				return balance;
			} catch (err) {
				console.error("查询 SPL Token 余额失败:", err);
				return 0;
			}
		},
		// 构建邀请码交易
		async inviteCodetransactionApi() {
			this.isButtonDisabled = true
			let data = {
				"amount": this.model.amount,
				"role": this.model.role,
				// "type": "usdc"
				"type": "usdt",
				"address": uni.getStorageSync('walletAddress'),
			}
			let res = {}
			res = await inviteCodetransaction(data)
			if (res.code == 200) {
				console.log(res, 'res inviteCodetransactionApi');
				let serializedTransaction = res.data.serializedTransaction.data
				if (serializedTransaction) {
					console.log('发送广播');
					const txBuffer = new Uint8Array(serializedTransaction);
					const transaction = Transaction.from(txBuffer);
					let signature = ''
					let signAndSendTransaction = {
						signature: ''
					}
					try {
						signAndSendTransaction = await window.solana.signAndSendTransaction(transaction);
					} catch (e) {
						console.log('e', e);
						this.isButtonDisabled = false
						uni.showToast({
							title: '拒绝交易',
							icon: "error"
						})
						return;
					}
					signature = signAndSendTransaction.signature
					console.log("交易签名:", signature);
					// 等待确认
					try {
						const confirmation = await connection.confirmTransaction(signature, 'confirmed')
						if (confirmation.value.err) {
							console.log('交易确认失败');
							this.isButtonDisabled = false
							uni.showToast({
								title: '交易不合法',
								icon: "error"
							})
							throw new Error('交易确认失败')
							return;
						}
						if (signature) {
							console.log('signature 交易存在', signature);
							this.signature = signature
							/* 保存记录 */
							this.inviteCodepurchaseApi()
						}
					} catch (err) {
						this.isButtonDisabled = false
						uni.showToast({
							title: '网络错误,请更换节点',
							icon: 'none'
						})
						console.log('err network', err);
					}
				}
			} else {
				this.isButtonDisabled = false
			}
		},
		// 方法用于格式化 publicKey 的显示
		formatPublicKey(key) {
			if (!key) return "";
			const start = key.slice(0, 4);
			const end = key.slice(-4);
			return `${start}...${end}`;
		},
		// 用户信息
		async getUserInfoApi() {
			let address = uni.getStorageSync('walletAddress')
			let res = await getUserInfo(address)
			this.model = {
				...this.model,
				...res.data
			}
		},
		// 获取价格
		async inviteCodeinfoApi() {
			let role = this.model.role
			let data = {
				"role": role,
				"address": uni.getStorageSync('walletAddress'),
			}
			let res = await inviteCodeinfo(data)
			if (res.code == 200) {
				this.model = {
					...this.model,
					...res.data
				}
				this.model.miniAmount = res.data.amount
			} else {
				console.log('失败');
				uni.showToast({
					title: "error",
					icon: "none"
				})
			}
		},
		/* 提交价格 */
		async inviteCodepurchaseApi() {
			let data = {
				"amount": this.model.amount,
				"hx": this.signature,
				"address": uni.getStorageSync('walletAddress'),
			}
			let res = await inviteCodepurchase(data)
			if (res.code == 200) {
				this.isButtonDisabled = false
				uni.showToast({
					title: "购买成功",
					icon: "none"
				})
				this.inviteCodeinfoApi()
				// uni.navigateTo({
				// 	url: '/pages/invitedList/invitedList'
				// })
			} else {
				console.log('失败');
				this.isButtonDisabled = false
				uni.showToast({
					title: "记录失败",
					icon: "none"
				})
			}
		},
		async getBtn() {
			/* 无资格 */
			// console.log(this.model.price,'this.model.price');
			// console.log(this.model.amount,'amount');
			if (this.model.price == 0 && this.model.amount == 0) {
				uni.showToast({
					title: '没有购买资格',
					icon: 'none',
					mask: true
				})
				return;
			}
			await this.getUsdcBalance()
			/* 钱不够 */
			if (this.balance < this.totalPrice) {
				uni.showToast({
					title: '账户 额度不足',
					icon: 'none'
				})
				return
			}
			// if (this.model.amount != 0 && this.model.role == 1 || this.model.role == 2 || this.model.role == 3)
			if (this.model.amount != 0 && this.model.price != 0) {
				// this.model.amount = 1
				// 构建邀请码交易
				// this.inviteCodetransactionApi()
				uni.$u.debounce(this.inviteCodetransactionApi, 500)
			} else {
				uni.showToast({
					title: '总价不能为0',
					icon: "none"
				})
			}
		},
		goBack() {
			uni.navigateBack()
		},
	},
	onLoad() { },
	async onShow() {
		// return await this.inviteCodepurchaseApi()
		// return await this.inviteCodetransactionApi()
		await this.getUserInfoApi()
		await this.inviteCodeinfoApi()
		if (this.model.price == 0 && this.model.amount == 0) {
			uni.showToast({
				title: '没有购买资格',
				icon: 'none',
				mask: true
			})
			return;
		}
	}
};
</script>

<style scoped lang="scss">
.headerBox {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.leftBox {
	display: flex;
	align-items: center;
	margin-left: 16rpx;
}

.oneImage {
	width: 129rpx;
	height: 129rpx;
}

.hello {
	font-weight: 800;
	font-size: 36rpx;
	color: #ffffff;
	line-height: 64rpx;
}

.recharge-tag {
	display: flex;
	// justify-content: center;
	justify-content: space-between;
	margin: 0 30rpx;

	.recharge-tag-left {
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 26rpx;
			color: #FFFFFF;
			line-height: 26rpx;
		}
	}

	.recharge-tag-right {
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 26rpx;
			color: #FFFFFF;
			line-height: 26rpx;
		}
	}
}

.mev-follow-robot-search-wrap {
	margin: 0 30rpx;
	height: 108rpx;
	background: #29313C;
	border-radius: 30rpx;
	border: 2rpx solid #6C7680;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 30rpx;

	.mev-follow-robot-search-wrap-icon {
		margin: 30rpx 20rpx 30rpx 30rpx;
		width: 48rpx;
		height: 48rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.mev-follow-robot-search-wrap-input {
		display: flex;
		align-items: center;

		input {
			color: white;
		}
	}

	.mev-follow-robot-search-wrap-select {
		display: flex;
		align-items: center;

		.mev-follow-robot-search-wrap-select-label {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 24rpx;
			color: #fff;
			// color: #45E5AF;
			line-height: 64rpx;
		}

		.mev-follow-robot-search-wrap-select-icon {
			width: 20rpx;
			height: 12rpx;
			margin-left: 16rpx;
			margin-right: 36rpx;
		}
	}
}

.recharge-header {
	display: flex;
	// align-items: center;
	// justify-content: space-between;
	margin: 0 30rpx;
	justify-content: space-between;



	.recharge-header-back-icon {
		margin-right: 26rpx;

		image {
			width: 22rpx;
			height: 38rpx;
		}
	}

	.recharge-header-title {
		text {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 36rpx;
			color: #FFFFFF;
			line-height: 36rpx;

		}
	}

	.recharge-header-subtitle {
		// vertical-align: bottom;
		display: flex;
		align-items: end;

		/* 使元素垂直居中 */
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #45E5AF;
			// line-height: 64rpx;
		}
	}

}




/*  */
.wallet-avatar-gap {
	border-radius: 40rpx;
	background-color: #4a90e2;
	width: 80rpx;
	height: 80rpx;
	margin-right: 31rpx;
}

.content {
	width: 100%;
	min-height: 100vh;
	background-color: #1f2630;
}

.claimBox {
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top: 50rpx;

	.claim1 {
		width: 22rpx;
		height: 38rpx;
		// margin-left: 28rpx;
	}

	.claim2 {
		font-weight: 500;
		font-size: 36rpx;
		color: #ffffff;
		// margin-left: 195rpx;
	}
}

.addressOne {
	display: flex;
	align-items: center;
	margin-top: 59rpx;
	margin-left: 30rpx;

	.tp {
		width: 100rpx;
		height: 100rpx;
	}

	.address {
		font-weight: 300;
		font-size: 36rpx;
		color: #ffffff;
		margin-left: 21rpx;
	}

	.down {
		width: 25rpx;
		height: 14rpx;
		margin-left: 20rpx;
	}
}

.picBox {
	width: 690rpx;
	height: 420rpx;

	// background-image: url("/static/home/nine.png");
	background: url('/static/home/nine.png') no-repeat;

	background-size: 100%;

	margin-left: 30rpx;
	margin-right: 30rpx;
	margin-top: 30rpx;

	.picOne {
		display: flex;
		align-items: center;
		padding-top: 30rpx;

		.pic1 {
			width: 44rpx;
			height: 48rpx;
			margin-left: 22rpx;
		}

		.num1 {
			font-size: 30rpx;
			color: #ffffff;
			margin-left: 11rpx;
		}

		.num2 {
			font-size: 48rpx;
			color: #ffffff;
			margin-left: 45rpx;
		}

		.pic2 {
			width: 35rpx;
			height: 23rpx;
			margin-left: 20rpx;
		}
	}

	.drawDownBox {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin-top: 63rpx;

		.drawOne {
			// margin-left: 46rpx;
			text-align: center;

			.one {
				font-size: 36rpx;
				color: #ffffff;
			}

			.one1 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}

		.drawTwo {
			// margin-left: 125rpx;
			text-align: center;

			.two {
				font-size: 36rpx;
				color: #ffffff;
			}

			.two2 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}

		.drawThree {
			// margin-left: 134rpx;
			text-align: center;

			.three {
				font-size: 36rpx;
				color: #ffffff;
			}

			.three3 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}
	}
}

.progress-container {
	width: 600rpx;
	display: flex;
	margin: 0 auto;
	align-items: center;
	// background-color: #333;
	border-radius: 10px;
	// overflow: hidden;
	// margin-left: 45rpx;
	// margin-top: 60rpx;
	position: relative;
	flex-direction: column;
}

.progress-bar {
	width: 600rpx;
	height: 20rpx;
	// background-color: #ffcc00;
	border-radius: 12px;

	background: linear-gradient(to right, #ffcc00 var(--difference-percentage), #1F2631 0%);
	/* 黄色 */
	transition: width 0.5s ease-in-out;
}

.percentage {
	// position: absolute;
	// top: 41%;


	// left: 40%;
	// right: 10px;

	font-size: 72rpx;
	color: #fcd434;
}

.submitBox {
	width: 690rpx;
	height: 88rpx;
	background: #29313C;
	border-radius: 44rpx;
	margin-top: 60rpx;
	margin-left: 30rpx;


	.submit {
		font-weight: bold;
		font-size: 36rpx;
		color: #0d081a;
		line-height: 80rpx;
		text-align: center;
	}
}

.active {
	background: #fcd434 !important;
}
</style>